<template>
  <div class="dashboard-container">
    <!-- 顶部：就诊趋势和年度统计 -->
    <div class="top-row">
      <div class="chart-card">
        <div ref="visitTrend" class="chart"></div>
      </div>
      <div class="chart-card">
        <div ref="recentYearsStats" class="chart"></div>
      </div>
    </div>

    <!-- 中部：病例类型和恢复情况并排 -->
    <div class="middle-row">
      <div class="chart-card">
        <div ref="caseType" class="chart"></div>
      </div>
      <div class="chart-card">
        <div ref="recoveryStatus" class="chart"></div>
      </div>
    </div>

    <!-- 底部：年龄段分析 -->
    <div class="bottom-row">
      <div class="chart-card">
        <div ref="ageGroupAnalysis" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import { usePatientStore } from '@/stores/patientStore';
import * as echarts from 'echarts';

const patientStore = usePatientStore();

// 定义图表引用
const visitTrend = ref(null);
const caseType = ref(null);
const recoveryStatus = ref(null);
const ageGroupAnalysis = ref(null);
const recentYearsStats = ref(null);

// 计算统计数据
const stats = computed(() => {
  const patients = patientStore.patients;
  const now = new Date();
  const currentYear = now.getFullYear();
  
  // 就诊数量趋势（最近6个月）
  const monthlyVisits = Array(6).fill(0).map((_, i) => {
    const month = now.getMonth() - i;
    const year = month < 0 ? currentYear - 1 : currentYear;
    const actualMonth = month < 0 ? 12 + month : month + 1;
    
    return patients.filter(p => {
      const visitDate = new Date(p.visitDate);
      return visitDate.getFullYear() === year && 
             visitDate.getMonth() + 1 === actualMonth;
    }).length;
  }).reverse();

  const monthNames = Array(6).fill(0).map((_, i) => {
    const month = now.getMonth() - 5 + i;
    const date = new Date(now.getFullYear(), month, 1);
    return date.toLocaleString('zh-CN', { month: 'short' });
  });

  // 病例类型统计（从purpose字段提取）
  const caseTypes = {
    '抑郁症': patients.filter(p => /抑郁/.test(p.purpose)).length,
    '焦虑症': patients.filter(p => /焦虑/.test(p.purpose)).length,
    '人际关系': patients.filter(p => /人际|社交/.test(p.purpose)).length,
    '学习问题': patients.filter(p => /学习|厌学/.test(p.purpose)).length,
    '其他': patients.length - patients.filter(p => 
      /抑郁|焦虑|人际|社交|学习|厌学/.test(p.purpose)
    ).length
  };

  // 患者恢复情况（从plan字段提取）
  const recoveryStats = {
    '显著改善': patients.filter(p => /显著|明显|很好|良好/.test(p.plan)).length,
    '有所改善': patients.filter(p => /有所改善|好转|进步/.test(p.plan)).length,
    '维持现状': patients.filter(p => /维持|继续观察/.test(p.plan)).length,
    '需要关注': patients.filter(p => /较差|严重|关注/.test(p.plan)).length
  };

  // 不同年龄段就诊数量分析
  const ageGroups = {
    '0-12岁': patients.filter(p => p.age <= 12).length,
    '13-18岁': patients.filter(p => p.age > 12 && p.age <= 18).length,
    '19-25岁': patients.filter(p => p.age > 18 && p.age <= 25).length,
    '26-35岁': patients.filter(p => p.age > 25 && p.age <= 35).length,
    '36+岁': patients.filter(p => p.age > 35).length
  };

  // 近几年就诊人数统计
  const yearlyVisits = {};
  for (let year = currentYear - 4; year <= currentYear; year++) {
    yearlyVisits[year] = patients.filter(p => {
      const visitYear = new Date(p.visitDate).getFullYear();
      return visitYear === year;
    }).length;
  }

  return {
    monthlyVisits,
    monthNames,
    caseTypes,
    recoveryStats,
    ageGroups,
    yearlyVisits
  };
});

// 初始化图表
const initChart = (el, options) => {
  const chart = echarts.init(el);
  chart.setOption(options);
  window.addEventListener('resize', () => chart.resize());
  return chart;
};

// 颜色配置
const colors = {
  blue: '#5470C6',
  red: '#EE6666',
  green: '#91CC75',
  orange: '#FAC858',
  purple: '#73C0DE',
  gray: '#9A60B4'
};

onMounted(() => {
  patientStore.fetchPatients().then(() => {
    // 就诊数量趋势 - 条形图
    initChart(visitTrend.value, {
      title: { 
        text: '近6个月就诊数量趋势',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { 
        type: 'category',
        data: stats.value.monthNames,
        axisLabel: { rotate: 45 }
      },
      yAxis: { type: 'value', name: '就诊人数' },
      series: [{
        name: '就诊人数',
        type: 'bar',
        data: stats.value.monthlyVisits,
        itemStyle: { color: colors.blue },
        barWidth: '60%',
        label: { show: true, position: 'top' }
      }]
    });

    // 病例类型统计 - 饼图
    initChart(caseType.value, {
      title: { 
        text: '病例类型分布',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      legend: { 
        orient: 'vertical',
        right: 10,
        top: 'middle',
        textStyle: { fontSize: 12 }
      },
      series: [{
        name: '病例类型',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['40%', '50%'],
        data: Object.entries(stats.value.caseTypes).map(([name, value]) => ({
          value,
          name,
          itemStyle: {
            color: name === '抑郁症' ? colors.red :
                  name === '焦虑症' ? colors.blue :
                  name === '人际关系' ? colors.green :
                  name === '学习问题' ? colors.orange : colors.purple
          }
        })),
        label: { show: true, formatter: '{b}: {c}' },
        emphasis: { scale: true, scaleSize: 10 }
      }]
    });

    // 患者恢复情况 - 环形图
    initChart(recoveryStatus.value, {
      title: { 
        text: '患者恢复情况',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      legend: { 
        orient: 'vertical',
        left: 'right',
        top: 'middle',
        textStyle: { fontSize: 12 }
      },
      series: [{
        name: '恢复情况',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['40%', '50%'],
        data: Object.entries(stats.value.recoveryStats).map(([name, value]) => ({
          value,
          name,
          itemStyle: {
            color: name === '显著改善' ? colors.green :
                  name === '有所改善' ? colors.blue :
                  name === '维持现状' ? colors.orange : colors.red
          }
        })),
        label: { show: true, formatter: '{b}: {c}' },
        emphasis: { scale: true, scaleSize: 10 }
      }]
    });

    // 不同年龄段就诊数量分析 - 横向条形图
    initChart(ageGroupAnalysis.value, {
      title: { 
        text: '各年龄段就诊分布',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'value', name: '就诊人数' },
      yAxis: { 
        type: 'category', 
        data: Object.keys(stats.value.ageGroups),
        axisLabel: { interval: 0 }
      },
      series: [{
        name: '就诊人数',
        type: 'bar',
        data: Object.values(stats.value.ageGroups),
        itemStyle: {
          color: function(params) {
            const colorList = [colors.red, colors.blue, colors.green, colors.orange, colors.purple];
            return colorList[params.dataIndex % colorList.length];
          }
        },
        barWidth: '60%',
        label: { show: true, position: 'right' }
      }]
    });

    // 近几年就诊人数统计 - 折线图
    initChart(recentYearsStats.value, {
      title: { 
        text: '近5年就诊人数趋势',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { 
        type: 'category',
        data: Object.keys(stats.value.yearlyVisits),
        boundaryGap: false
      },
      yAxis: { type: 'value', name: '就诊人数' },
      series: [{
        name: '就诊人数',
        type: 'line',
        data: Object.values(stats.value.yearlyVisits),
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: { color: colors.red },
        lineStyle: { width: 3 },
        label: { show: true, position: 'top' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(238, 102, 102, 0.5)' },
            { offset: 1, color: 'rgba(238, 102, 102, 0.1)' }
          ])
        }
      }]
    });
  });
});
</script>

<style scoped>
.dashboard-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.top-row, .middle-row, .bottom-row {
  display: flex;
  gap: 20px;
  width: 100%;
}

.top-row, .bottom-row {
  flex-direction: row;
}

.middle-row {
  flex-direction: row;
  min-height: 400px;
}

.chart-card {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.chart {
  flex: 1;
  width: 100%;
  min-height: 300px;
}

@media (max-width: 1200px) {
  .top-row, .middle-row, .bottom-row {
    flex-direction: column;
  }
  
  .chart-card {
    width: 100%;
  }
}
</style>